from django.shortcuts import render, redirect, HttpResponse
from .forms import *
from django.contrib.auth import authenticate, login, logout
from django.views import View
from .check_code import create_validate_code
from io import BytesIO
from django.http import JsonResponse
import datetime
from django.contrib.sessions.models import Session
from threading import Timer

def delsession(id):
    # globalsetting = int(GlobalSetting.objects.first().userOnlineLimit)
    session_dict = []
    for session in Session.objects.filter(expire_date__gt=datetime.datetime.utcnow()).order_by('-expire_date'):
        data = session.get_decoded().get('_auth_user_id')
        if data and int(data) == id:
            session_dict.append(session)
    print(session_dict)
    # if session_dict.__len__() > globalsetting:
    #     for delsession in session_dict[globalsetting:]:
    #         delsession.delete()

def check_code(request):
    """
    获取验证码
    :param request:
    :return:
    """
    stream = BytesIO()
    # 生成图片 img、数字代码 code，保存在内存中，而不是 Django 项目中
    img, code = create_validate_code()
    img.save(stream, 'PNG')

    # 写入 session
    request.session['valid_code'] = code
    print(code)
    return HttpResponse(stream.getvalue())


class user_login(View):
    def get(self, request):
        user_login_form = UserLoginForm()
        return render(request, 'UserLogin.html', locals())

    def post(self, request):
        res = {'isSuccess': False, 'msg': None}
        user_login_form = UserLoginForm(data=request.POST)
        if user_login_form.is_valid():
            # .cleaned_data 清洗出合法数据
            data = user_login_form.cleaned_data
            print('data',data)
            if data['captcha'].upper() == request.session.get('valid_code').upper():
                user = authenticate(username=data['username'], password=data['password'])
                print('user',user)
                if user:
                    if user.is_active:
                        if user.is_superuser:
                            res['msg'] = '用户名或密码错误'
                            return JsonResponse(res)
                        # 将用户数据保存在 session 中，即实现了登录动作
                        login(request, user)
                        print(request.session.session_key)
                        # t = Timer(5, delsession, (user.id,))
                        # t.start()
                        res['isSuccess'] = True
                    else:
                        res['msg'] = '账号已禁用'
                        # return JsonResponse(res)
                else:
                    res['msg'] = '用户名或密码错误'
                    # return JsonResponse(res)
            else:
                res['msg'] = '验证码错误或已过期'
                # return JsonResponse(res)
        else:
            res['msg'] = '用户名或密码不合法'
        return JsonResponse(res)

    # else:
    #     return HttpResponse("账号或密码输入不合法")


class admin_login(View):
    def post(self, request):
        res = {'isSuccess': False, 'msg': None}
        user_login_form = UserLoginForm(data=request.POST)
        if user_login_form.is_valid():
            # .cleaned_data 清洗出合法数据
            data = user_login_form.cleaned_data
            if data['captcha'].upper() == request.session.get('valid_code').upper():
                user = authenticate(username=data['username'], password=data['password'])
                if user:
                    if user.is_active:
                        if not user.is_superuser:
                            res['msg'] = '用户名或密码错误'
                            return JsonResponse(res)
                        # 将用户数据保存在 session 中，即实现了登录动作
                        login(request, user)
                        print(request.session.session_key,user.id)
                        res['isSuccess'] = True
                        return JsonResponse(res)
                    else:
                        res['msg'] = '账号已禁用'
                        return JsonResponse(res)
                else:
                    res['msg'] = '用户名或密码错误'
                    return JsonResponse(res)
            else:
                res['msg'] = '验证码错误或已过期'
                return JsonResponse(res)
        else:
            res['msg'] = '用户名或密码不合法'
            return JsonResponse(res)

    def get(self, request):
        user_login_form = UserLoginForm()
        return render(request, 'AdminLogin.html', locals())


def user_logout(request):
    logout(request)
    return redirect('home:home_page')


class user_register(View):
    def post(self, request):
        res = {'isSuccess': False, 'msg': None}
        user_register_form = UserRegisterForm(data=request.POST)
        if user_register_form.is_valid():
            data = user_register_form.cleaned_data
            if data['captcha'].upper() == request.session.get('valid_code').upper():
                new_user = user_register_form.save(commit=False)
                # 设置密码
                new_settings = GlobalSetting.objects.all().first()
                # new_user.uploadLimit = new_settings.uploadLimit
                # new_user.expireTime = datetime.datetime.now()+datetime.timedelta(days=int(new_settings.trialDays))
                new_user.set_password(user_register_form.cleaned_data['password'])

                # 保存好数据后立即登录并返回页面
                res['isSuccess'] = True
                if new_settings.userIsCheckOpen:
                    res['msg'] = "注册成功，请等待管理员审核"
                    new_user.is_active = False
                    new_user.save()
                else:
                    res['msg'] = "注册成功"
                    new_user.save()
                    login(request, new_user)
                # new_user.save()
                return JsonResponse(res)
            else:
                res['msg'] = '验证码错误或已过期'
                return JsonResponse(res)
        else:
            res['msg'] = str(user_register_form.errors.as_data).split('of ')[-1][:-1].split(': ')[1][:-1].replace("['",'').replace("。']",'')
            print(type(user_register_form.errors.as_data),'++++',res['msg'])
            print(user_register_form.errors.as_data)
            return JsonResponse(res)


    def get(self, request):
        user_register_form = UserRegisterForm()
        context = {'form': user_register_form}
        return render(request, 'UserReg.html', context)


class business_login(View):
    def get(self, request):
        user_login_form = UserLoginForm()
        return render(request, 'BusinessLogin.html', locals())

    def post(self, request):
        res = {'isSuccess': False, 'msg': None}
        user_login_form = UserLoginForm(data=request.POST)
        if user_login_form.is_valid():
            # .cleaned_data 清洗出合法数据
            data = user_login_form.cleaned_data
            print('data',data)
            if data['captcha'].upper() == request.session.get('valid_code').upper():
                user = authenticate(username=data['username'], password=data['password'])
                print('user',user)
                if user:
                    if user.is_active:
                        if user.is_superuser:
                            res['msg'] = '用户名或密码错误'
                            return JsonResponse(res)
                        else:
                            # 将用户数据保存在 session 中，即实现了登录动作
                            login(request, user)
                            print(request.session.session_key)
                            res['isSuccess'] = True
                            # return JsonResponse(res)
                    else:
                        res['msg'] = '账号已禁用'
                        # return JsonResponse(res)
                else:
                    res['msg'] = '用户名或密码错误'
                    # return JsonResponse(res)
            else:
                res['msg'] = '验证码错误或已过期'
                # return JsonResponse(res)
        else:
            res['msg'] = '用户名或密码不合法'
        return JsonResponse(res)



class business_register(View):
    def post(self, request):
        res = {'isSuccess': False, 'msg': None}
        business_register_form = BusinessRegisterForm(data=request.POST)
        if business_register_form.is_valid():
            data = business_register_form.cleaned_data
            if data['captcha'].upper() == request.session.get('valid_code').upper():
                new_user = business_register_form.save(commit=False)
                # 设置密码
                new_settings = GlobalSetting.objects.all().first()
                new_user.set_password(business_register_form.cleaned_data['password'])
                # 保存好数据后立即登录并返回页面
                res['isSuccess'] = True
                if new_settings.businessIsCheckOpen:
                    res['msg'] = "注册成功，请等待管理员审核"
                    new_user.is_active = False
                    new_user.save()
                else:
                    res['msg'] = "注册成功"
                    new_user.save()
                    login(request, new_user)
                # new_user.save()
                return JsonResponse(res)
            else:
                res['msg'] = '验证码错误或已过期'
                return JsonResponse(res)
        else:
            res['msg'] = str(business_register_form.errors.as_data).split('of ')[-1][:-1].split(': ')[1][:-1].replace("['",'').replace("。']",'')
            print(type(business_register_form.errors.as_data),'++++',res['msg'])
            print(business_register_form.errors.as_data)
            return JsonResponse(res)


    def get(self, request):
        businesstypes = BusinessType.objects.all().order_by('uploadTime')
        print(businesstypes.values('id','category'))
        business_register_form = BusinessRegisterForm()
        context = {'form': business_register_form,'types':businesstypes}
        return render(request, 'BusinessReg.html', context)
